from django.http import JsonResponse, HttpResponseForbidden, HttpResponse
from django.shortcuts import render,redirect
from django.views import View
from meiduo_mall.utils.log import logger_out
from .models import Area
from meiduo_mall.utils.response_code import RETCODE
from django.core.cache import cache
from . import constants


# 获取查询的地址
class AreasView (View):
    def get(self, request):
        # 获取area_id
        area_id = request.GET.get('area_id')
        if area_id is None:
            # 先读取缓存里面的province_list,如果没有再进行查询
            province_list = cache.get('province_list')
            # 如果缓存中没有数据则进行查询，否则直接将缓存中的数据返回
            if province_list is None:
                # 如果area_id为空，则为查询省份
                try:
                    # 利用模型类查询省份数据,查询area对象的列表
                    province_moder_list = Area.objects.filter(parent__isnull=True)
                    # 序列化省级城市，组成json数据
                    province_list = []
                    for province_model in province_moder_list:
                        province_list.append({"id": province_model.id, "name": province_model.name})
                except Exception as e:
                    logger_out.warning(e)
                    return JsonResponse({"code": RETCODE.DBERR,
                                         'errmsg': "省份错误"})
                # 将数据存储在缓存中
                cache.set('province_list', province_list, constants.AREA_CASH_EXPIRES)
            return JsonResponse({"code": RETCODE.OK,
                                 'errmsg': "OK",
                                'province_list': province_list,
                                })
        else:
            sub_data = cache.get('sub_data_' + area_id)
            if sub_data is None:
                # 如果area_id不为空，则为城市
                try:
                    # 获取id为area_id的外键对象
                    parent_model = Area.objects.get(id=area_id)
                    # 注意subs是别名。在这里有别名则利用别名查询，否则用对象名_set模式查询
                    # sub_model_list = parent_model.parent_set.all()
                    sub_model_list = parent_model.subs.all()

                    # 序列化城市或区数据
                    sub_list = []
                    for sub_model in sub_model_list:
                        sub_list.append({'id': sub_model.id, 'name': sub_model.name})
                    sub_data = {
                        'id': parent_model.id,
                        'name': parent_model.name,
                        'subs': sub_list
                    }
                except Exception as e:
                    logger_out.warning(e)
                    return JsonResponse({"code": RETCODE.DBERR,
                                        'errmsg': "城市区域错误"})
                cache.set('sub_data_' + area_id, sub_data, constants.AREA_CASH_EXPIRES)
            return JsonResponse({"code": RETCODE.OK,
                                'errmsg': "OK",
                                'sub_data': sub_data, })



